package SpringBoot.spring_boot_starter_websocket.D02_服务端广播.config.handler;

import java.net.URI;
import java.security.Principal;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import com.titan.core.utils.io.ConsoleUtils;

/**
 * 
 *
 * @author 周成功
 *
 */
public class WebSocketHandshakeHandler extends DefaultHandshakeHandler {
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        URI uri = request.getURI();
        // uri示例 : http://127.0.0.1:8023/WebSocketEndpoint/295/htsnvlac/websocket
        String id = null;
        if (uri != null) {
            String query = uri.getPath();
            String[] pairs = query.split("/");
            id = pairs[3];
        }
        ConsoleUtils.method(WebSocketHandshakeHandler.class, "determineUser", "uri", uri, "id", id);
        if(StringUtils.isEmpty(id)) {
            return super.determineUser(request, wsHandler, attributes);
        } else {
            MyPrincipal principal = new MyPrincipal();
            principal.setName(id);
            return principal;
        }
    }
    
    
    class MyPrincipal implements Principal {
        private String name;

        @Override
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            MyPrincipal that = (MyPrincipal) o;
            return name != null ? name.equals(that.name) : that.name == null;
        }

        @Override
        public int hashCode() {
            return name != null ? name.hashCode() : 0;
        }
    }
}
